<template>
  <div>
    <el-dialog
        title="上传文件"
        v-el-drag-dialog
        width="40%"
        :visible="mcShow.uploadshp==='loadshp'"
        :before-close="handleClose">
			<span>
				<el-upload class="upload-demo"
                   ref="upload"
                   drag
                   action
                   :multiple="false"
                   :auto-upload="false"
                   :limit="5"
                   :on-success="handleFilUploadSuccess"
                   :on-remove="handleRemove"
                   :on-change="fileChange">
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<div class="el-upload__tip" slot="tip">
            <p>1.请上传zip压缩包；</p>
            <p>2.确保上传的数据为2000国家大地坐标系；</p>
            <p>3.上传的zip文件至少包含：.shp、.dbf、.shx、.prj文件。</p>
          </div>
				</el-upload>
			</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpload">确 定</el-button>
				<el-button @click="handleClose">取 消</el-button>
			</span>

    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from "@/directive/el-dragDialog/";
import Bus from "@/utils/bus";
import {uploadShpFileZip} from "@/api/portal/ioGisFile";

export default {
  name: "Loadshp",
  data() {
    return {
      /*isShow:this.isShowLoad,*/
      fileList: [],
      dialogVisible: false,
      fileType: ["zip"],
      fileSize:10,
    };
  },
  props: {
    map: {
      type: Object,
      default() {
        return {}
      }
    },
    mcShow: {
      type: Object,
      default() {
        return {
          uploadshp: 'close',
        }
      }
    },
    handleLoadFeatoMap: {
      type: Function,
    },
    /*isShowLoad:null*/
  },
  directives: {//到这里了，看看自定义组件怎么个用法
    elDragDialog,
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType.length > 0) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        let isTypeOk = false;
        for (let i = 0; i < this.fileType.length; i++) {
          if (fileExtension === this.fileType[i]) {
            isTypeOk = true;
          }
        }
        if (isTypeOk===false) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    fileChange(file) {
      let tyTrue = this.handleBeforeUpload(file);
      if (tyTrue === false) {
        return;
      }
      let existFile = this.fileList.find(f => f.name === file.name)//如果文件名重复
      if (typeof (existFile) == "undefined" || existFile === null) {
        this.fileList.push(file);
      } else {
        this.$message.error('当前文件已经存在，将不会上传该文件！');
        // this.fileList.pop()

      }
    },
    handleClose(done) {
      var that = this;
      that.mcShow.uploadshp = 'close';
    },
    handleRemove(file, fileList) {
      //  console.log(file, fileList);
      fileList.splice(file);
    },
    submitUpload() {
      let that = this;
      let fd = new FormData();
      //不允许上传多个文件，只读取第一个
      // that.fileList.forEach(item => {
      //   //文件信息中raw才是真的文件
      //   fd.append("files", item.raw);
      // });
      fd.append("files", that.fileList[0].raw);
      uploadShpFileZip(fd).then(res => {
        if (res.code === 200) {
          if (res.data.status === "error") {
            this.$message.error(res.data.msg)
          } else if (res.data.status === 400) {
            this.$message.error("上传shp文件有错误，请检查文件是否正确。  " + res.data.message)
          }
          let props = res.data.queryData[0].data.props;//可以上传多个shp，但是只获取第一个。
          let format = new ol.format.WKT();
          let sumArea = 0;
          //先计算一遍面积
          for (let index in props) {
            let prop = props[index]
            let geowkt = prop.the_geom//这是wkt格式的
            let featuresSum = format.readFeature(geowkt, {
              dataProjection: 'EPSG:' + res.data.epsgId,
              featureProjection: 'EPSG:4530'
            })
            let farea = ol.sphere.getArea(featuresSum.getGeometry());
            sumArea += farea;
          }
          //266666680对应40万亩
          if (sumArea > 266666680) {
            this.$message.error('上传文件面积过大，请减少图斑后重新上传')
            return;
          }

          let features = [];
          for (let index in props) {
            let prop = props[index];
            let geowkt = prop.the_geom;//这是wkt格式的

            let feature = format.readFeature(geowkt, {
              dataProjection: "EPSG:" + res.data.epsgId,
              featureProjection: that.map.getView().getProjection().getCode()
            });
            feature.set("featureid", "inputshp");
            feature.setStyle(new ol.style.Style({
              fill: new ol.style.Fill({
                color: 'rgba(250,250,250,0.2)'
              }),
              stroke: new ol.style.Stroke({
                color: '#00ffff', //'#d74a4a',
                width: 2
              }),
              image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                  color: '#00ffff'
                })
              })
            }));
            features.push(feature);
          }
          this.handleLoadFeatoMap(features);
          // let geojsonFormat = new ol.format.GeoJSON();
          // let featuresGeojson = geojsonFormat.writeFeatures(features);
          // var param = {
          //   "geojson": featuresGeojson,
          //   "operatetype": "temp",
          //   "name": res.data.fileName
          // };
          // Bus.$emit('updateTempLayer', param);//在Catalog里显示
          this.$message.success("上传成功")
          this.mcShow.uploadshp = 'close';
        } else {
          this.$message.error('解析文件失败，请检查文件正确性')
        }
      }).catch((error) => {
        // catch 指请求出错的处理
        console.log(error);
      });
    },
    // 文件上传成功时的函数
    handleFilUploadSuccess(res, file, fileList) {
      console.log(res, file, fileList)
    },
    // 处理文件上传的函数
    handleUpload() {
      this.submitUpload()

    }
  }
}
</script>

<style scoped>
.upload-demo .el-upload__input {
  display: none !important;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  text-align: left;
  margin-left: 20%;
}
</style>
